Program C++: Advanced by N. Goodrum Robert
Author:N. Goodrum, Robert [N. Goodrum, Robert]
Language: eng
Format: epub
Publisher: UNKNOWN
Published: 2020-10-21T16:00:00+00:00
10: Name Control
Creating names is a fundamental activity in
programming, and when a project gets large, the number of names can easily be overwhelming.
C++ allows you a great deal of control over the creation and visibility of names, where storage for those names is placed, and linkage for names.
The static keyword was overloaded in C before people knew what the term âoverloadâ meant, and C++ has added yet another meaning. The underlying concept with all uses of static seems to be âsomething that holds its positionâ (like static electricity), whether that means a physical location in memory or visibility within a file.
In this chapter, youâll learn how static controls storage and visibility, and an improved way to control access to names via C++âs namespace feature. Youâll also find out how to use functions that were written and compiled in C.
Static elements from C
In both C and C++ the keyword static has two basic meanings, which unfortunately often step on each otherâs toes:
1. Allocated once at a fixed address; that is, the object is created in a special static data area rather than on the stack each time a function is called. This is the concept of static storage .
2. Local to a particular translation unit (and local to a class scope in C++, as you will see later). Here, static controls the visibility of a name, so that name cannot be seen outside the translation unit or class. This also describes the concept of linkage , which determines what names the linker will see.
This section will look at the above meanings of static as they were inherited from C.
static variables inside functions
When you create a local variable inside a function, the compiler allocates storage for that variable each time the function is called by moving the stack pointer down an appropriate amount. If there is an initializer for the variable, the initialization is performed each time that sequence point is passed.
Sometimes, however, you want to retain a value between function calls. You could accomplish this by making a global variable, but then that variable would not be under the sole control of the function. C and C++ allow you to create a static object inside a function; the storage for this object is not on the stack but instead in the programâs static data area. This object is initialized only once, the first time the function is called, and then retains its value between function invocations. For example, the following function returns the next character in the array each time the function is called:
//: C10:StaticVariablesInfunctions.cpp #include "../require.h"
#include <iostream>
using namespace std;
char oneChar(const char* charArray = 0) { static const char* s;
if(charArray) {
s = charArray;
return *s;
}
else
require(s, "un-initialized s");
if(*s == '